package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final StringRedisTemplate stringRedisTemplate;

    private final CacheClient cacheClient;

    //创建线程池
//    private static final ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {
        //缓存穿透
//        Shop shop = queryWithPassThrough(id);
        //缓存重建解决缓存击穿
//        Shop shop = queryWithMutexLock(id);
        //逻辑过期解决缓存击穿逻辑
        Shop shop = cacheClient.queryWithPassThrough(
                RedisConstants.CACHE_SHOP_KEY, id, Shop.class,this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.SECONDS);
        if (shop == null) {
            return Result.fail("商户不存在");
        }
        return Result.ok(shop);
    }

    /**
     * 逻辑过期解决缓存击穿逻辑
     * @param id
     * @return
     */
//    public Shop queryWithLogicalExpire(Long id) {
//        //1.在redis中查询商户信息
//        String s = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//        //2.判断商户是否存在
//        if (StrUtil.isBlank(s)) {
//            //3.商户不存在，直接返回空值
//            return null;
//        }
//        //4.命中，将json数据反序列化为对象
//        RedisData data = JSONUtil.toBean(s, RedisData.class);
//        JSONObject shopJson = (JSONObject) data.getData();
//        Shop shop = JSONUtil.toBean(shopJson, Shop.class);
//        //5.判断是否过期
//        if (data.getExpireTime().isAfter(LocalDateTime.now())) {
//            //6.未过期，直接返回对象
//            return shop;
//        }
//        //6。过期，尝试获取互斥锁
//        boolean isLock = tryLock(RedisConstants.LOCK_SHOP_KEY + id);
//        //7.判断是否获取成功
//        if (isLock) {
//           //获取互斥锁成功，开启独立线程，实现缓存重建
//            executorService.submit(() -> {
//                try {
//                    //重新写入redis
//                    this.saveShop2Redis(id, RedisConstants.LOCK_SHOP_TTL);
//                    //释放锁
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }finally {
//                    unLock(RedisConstants.LOCK_SHOP_KEY + id);
//                }
//            });
//        }
//        //8.如果获取失败，说明没有其他线程正在写入，可以返回数据
//        return shop;
//    }

    /**
     * 缓存重建解决缓存击穿逻辑
     * @param id
     * @return
     */
//    public Shop queryWithMutexLock(Long id) {
//        //1.在redis中查询商户信息
//        String s = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//        //2.判断商户是否存在
//        if (StrUtil.isNotBlank(s)) {
//            //3.商户存在，直接返回
//            Shop shop = JSONUtil.toBean(s, Shop.class);
//            return shop;
//        }
//        //判断是否命中空值
//        if (s != null) {
//            //4.商户不存在，返回错误
//            return null;
//        }
//        //4.实现缓存重建
//        //4.1.获取互斥锁
//        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
//        Shop shop = null;
//        try {
//            boolean isLock = tryLock(lockKey);
//            //4.2.判断是否获取锁成功
//            if (!isLock) {
//                //4.3.获取锁不成功，休眠重试
//                Thread.sleep(50);
//                //进入递归
//                return queryWithMutexLock(id);
//            }
//            //4.4.获取成功，查询数据库
//            shop = getById(id);
//            //模拟重建延迟
//            Thread.sleep(200);
//            //5.数据库中不存在，返回错误
//            if (shop == null) {
//                //解决缓存穿透问题
//                //1将空值写入redis
//                stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
//                //2.返回错误
//                return null;
//            }
//            //6.数据库中存在，写入redis
//            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            //7.释放锁
//            unLock(lockKey);
//        }
//
//        //8.返回商户信息
//        return shop;
//
//    }

    /**
     * 缓存穿透解决逻辑
     * @param id
     * @return
     */
//    public Shop queryWithPassThrough(Long id) {
//        //1.在redis中查询商户信息
//        String s = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);
//        //2.判断商户是否存在
//        if (StrUtil.isNotBlank(s)) {
//            //3.商户存在，直接返回
//            Shop shop = JSONUtil.toBean(s, Shop.class);
//            return shop;
//        }
//        //判断是否命中空值
//        if (s != null) {
//            //4.商户不存在，返回错误
//            return null;
//        }
//        //4.商户不存在，查询数据库
//        Shop shop = getById(id);
//        //5.数据库中不存在，返回错误
//        if (shop == null) {
//            //解决缓存穿透问题
//            //1将空值写入redis
//            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
//            //2.返回错误
//            return null;
//        } else {
//            //6.数据库中存在，写入redis
//            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//            //7.返回商户信息
//            return shop;
//        }
//    }

    /**
     * 尝试获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 解锁
     * @param key
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 将店铺信息写入redis(实现逻辑过期解决缓存击穿问题)
     * @param id
     * @param expireSeconds
     */
    public void saveShop2Redis(Long id, Long expireSeconds) {
        //1.查询店铺数据
        Shop shop = getById(id);
        //模拟延迟时间
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("商户id不能为空");
        }
        //1.更新数据库
        updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            //不需要坐标查询，根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            //返回数据
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //3。查询redis 根据距离进行排序 分页 产生结果：shopId、distance
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                //GEOSEARCH key x y radius unit COUNT count [ASC|DESC] [WITHCOORD] [WITHDIST] [WITHHASH]
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
                                .includeDistance()
//                                .includeCoordinates()
                                .limit(end) //获取前end个
                );
        //4.获取当前页的店铺id
        if(results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        //健壮型判断
        if(content.isEmpty()|| content.size()<=from) {
            return Result.ok(Collections.emptyList());
        }
        //4.1 截取从from 到 end的部分
        List<Long> ids =new ArrayList<>(content.size());
        Map<String, Distance> distanceMap = new HashMap<>(content.size());
        content.stream().skip(from).forEach(result->{
            //4.2 获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            //4.3 获取店铺距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        //5.根据id查询shop
        String s = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + s + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        //6.返回
        return Result.ok(shops);

    }
}
